import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import { getCurrentUser, isAdmin } from '@/middleware/auth';
import { User } from '@/lib/db/auth-schema';
import { AuthService } from '@/lib/auth';

/**
 * 获取用户列表
 * GET /api/admin/users
 */
export async function GET(request: NextRequest) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果中间件没有设置用户信息，直接验证token
    if (!currentUser) {
      const token = request.headers.get('authorization')?.replace('Bearer ', '') ||
                   request.cookies.get('auth-token')?.value;
      
      if (!token) {
        return NextResponse.json(
          { success: false, error: '权限不足' },
          { status: 403 }
        );
      }
      
      const tokenResult = await AuthService.verifyToken(token);
      if (!tokenResult.valid || !tokenResult.payload) {
        return NextResponse.json(
          { success: false, error: '权限不足' },
          { status: 403 }
        );
      }
      
      currentUser = tokenResult.payload;
    }
    
    if (!isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');
    const search = searchParams.get('search') || '';
    const role = searchParams.get('role') || '';
    const status = searchParams.get('status') || '';
    const sortBy = searchParams.get('sortBy') || 'created_at';
    const sortOrder = searchParams.get('sortOrder') || 'desc';

    const offset = (page - 1) * limit;

    const db = await getDb();

    // 构建查询条件
    let whereClause = 'WHERE 1=1';
    const params: any[] = [];

    if (search) {
      whereClause += ' AND (username LIKE ? OR email LIKE ? OR display_name LIKE ?)';
      const searchPattern = `%${search}%`;
      params.push(searchPattern, searchPattern, searchPattern);
    }

    if (role) {
      whereClause += ' AND role = ?';
      params.push(role);
    }

    if (status) {
      whereClause += ' AND status = ?';
      params.push(status);
    }

    // 获取用户列表
    const usersQuery = `
      SELECT 
        id, username, email, display_name, role, status, avatar,
        last_login_at, created_at, updated_at
      FROM users 
      ${whereClause}
      ORDER BY ${sortBy} ${sortOrder.toUpperCase()}
      LIMIT ? OFFSET ?
    `;

    // 构建查询过滤器
    const filter: any = {};
    if (search) {
      filter.$or = [
        { username: { $regex: search, $options: 'i' } },
        { email: { $regex: search, $options: 'i' } },
        { display_name: { $regex: search, $options: 'i' } }
      ];
    }
    if (role) filter.role = role;
    if (status) filter.status = status;

    // 获取用户列表
    const usersResult = await db.findMany<User>('users', filter, {
      page,
      pageSize: limit,
      sortBy,
      sortOrder: sortOrder as 'asc' | 'desc'
    });
    const users = usersResult.success ? usersResult.data || [] : [];

    // 获取总数
    const countResult = await db.count('users', filter);
    const total = countResult.success ? countResult.data || 0 : 0;

    // 获取角色统计 - 简化版本，获取所有用户然后统计
    const allUsersResult = await db.findMany<User>('users', {});
    const allUsers = allUsersResult.success ? allUsersResult.data || [] : [];
    const roleStats = allUsers.reduce((acc: any[], user) => {
      const existing = acc.find(item => item.role === user.role);
      if (existing) {
        existing.count++;
      } else {
        acc.push({ role: user.role, count: 1 });
      }
      return acc;
    }, []);

    // 获取状态统计
    const statusStats = allUsers.reduce((acc: any[], user) => {
      const existing = acc.find(item => item.status === user.status);
      if (existing) {
        existing.count++;
      } else {
        acc.push({ status: user.status, count: 1 });
      }
      return acc;
    }, []);

    return NextResponse.json({
      success: true,
      data: users,
      total,
      page,
      limit,
      stats: {
        total: allUsers.length,
        active: statusStats.find(s => s.status === 'active')?.count || 0,
        inactive: statusStats.find(s => s.status === 'inactive')?.count || 0,
        banned: statusStats.find(s => s.status === 'banned')?.count || 0,
        roles: roleStats.reduce((acc: Record<string, number>, item) => {
          acc[item.role] = item.count;
          return acc;
        }, {})
      }
    });

  } catch (error) {
    console.error('获取用户列表失败:', error);
    return NextResponse.json(
      { success: false, error: '获取用户列表失败' },
      { status: 500 }
    );
  }
}

/**
 * 创建新用户
 * POST /api/admin/users
 */
export async function POST(request: NextRequest) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果中间件没有设置用户信息，直接验证token
    if (!currentUser) {
      const token = request.headers.get('authorization')?.replace('Bearer ', '') ||
                   request.cookies.get('auth-token')?.value;
      
      if (!token) {
        return NextResponse.json(
          { success: false, error: '权限不足' },
          { status: 403 }
        );
      }
      
      const tokenResult = await AuthService.verifyToken(token);
      if (!tokenResult.valid || !tokenResult.payload) {
        return NextResponse.json(
          { success: false, error: '权限不足' },
          { status: 403 }
        );
      }
      
      currentUser = tokenResult.payload;
    }
    
    if (!isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const body = await request.json();
    const { username, email, password, role, display_name, status } = body;

    // 验证必填字段
    if (!username || !email || !password) {
      return NextResponse.json(
        { success: false, error: '用户名、邮箱和密码为必填项' },
        { status: 400 }
      );
    }

    // 验证角色
    const validRoles = ['super_admin', 'admin', 'editor', 'user', 'guest'];
    if (role && !validRoles.includes(role)) {
      return NextResponse.json(
        { success: false, error: '无效的角色' },
        { status: 400 }
      );
    }

    const db = await getDb();

    // 检查用户名是否已存在
    const existingUsernameResult = await db.findOne<User>('users', { username });
    const existingEmailResult = await db.findOne<User>('users', { email });
    
    if (existingUsernameResult.success && existingUsernameResult.data) {
      return NextResponse.json(
        { success: false, error: '用户名已存在' },
        { status: 409 }
      );
    }
    
    if (existingEmailResult.success && existingEmailResult.data) {
      return NextResponse.json(
        { success: false, error: '邮箱已存在' },
        { status: 409 }
      );
    }



    // 创建用户
    const bcrypt = require('bcryptjs');
    const userId = crypto.randomUUID();
    const hashedPassword = await bcrypt.hash(password, 12);
    const now = new Date().toISOString();

    // 创建用户数据
    const userData: Partial<User> = {
      id: userId,
      username,
      email,
      password_hash: hashedPassword,
      role: (role || 'user') as User['role'],
      display_name: display_name || username,
      status: (status || 'active') as User['status'],
      created_at: now,
      updated_at: now
    };

    const createResult = await db.create<User>('users', userData);

    if (!createResult.success) {
      return NextResponse.json(
        { success: false, error: '创建用户失败' },
        { status: 500 }
      );
    }

    // 获取创建的用户信息（不包含密码）
    const { password_hash, ...newUser } = createResult.data!;

    return NextResponse.json({
      success: true,
      data: newUser,
      message: '用户创建成功'
    });

  } catch (error) {
    console.error('创建用户失败:', error);
    return NextResponse.json(
      { success: false, error: '创建用户失败' },
      { status: 500 }
    );
  }
}